#include <stdio.h>
#include <mysql/mysql.h>
#include "stack.h"
#include <mysql/mysql.h>
#include <stdio.h>
#include <string.h>

int ls_command(MYSQL* conn, DirStack* stack, const char* user_name, char* result) {
    int p_id;
    if (get_top(stack, &p_id) != 0) {
        strcpy(result, "路径栈为空\n");
        return -1;
    }

    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) {
        strcpy(result, "mysql_stmt_init 失败\n");
        return -1;
    }

    const char* sql = "SELECT name, is_dir FROM nodes WHERE user_name=? AND p_id=?";
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        sprintf(result, "准备SQL失败: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void*)user_name;
    bind[0].buffer_length = strlen(user_name);

    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = (void*)&p_id;

    if (mysql_stmt_bind_param(stmt, bind) != 0) {
        sprintf(result, "绑定参数失败: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    if (mysql_stmt_execute(stmt) != 0) {
        sprintf(result, "执行查询失败: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    char name[256];
    int is_dir;

    MYSQL_BIND res[2];
    memset(res, 0, sizeof(res));

    res[0].buffer_type = MYSQL_TYPE_STRING;
    res[0].buffer = name;
    res[0].buffer_length = sizeof(name);

    res[1].buffer_type = MYSQL_TYPE_LONG;
    res[1].buffer = &is_dir;

    if (mysql_stmt_bind_result(stmt, res) != 0) {
        sprintf(result, "绑定结果失败: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    // 清空 result
    result[0] = '\0';
char line[3000] = "";  // 大 buffer 用于装所有行
char temp[256];

while (mysql_stmt_fetch(stmt) == 0) {
    if (is_dir)
        snprintf(temp, sizeof(temp), "%s/  ", name);  // 目录加斜杠
    else
        snprintf(temp, sizeof(temp), "%s  ", name);   // 文件直接输出
    strncat(result, temp, sizeof(line) - strlen(line) - 1);  // 累加到 result
}


    // 拼接输出
    mysql_stmt_close(stmt);
    return 0;
}

